// main.cpp
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Exception.h"
#include <iostream>

#include <memory>


#include <stdio.h>
#include "zlog.h"


int zlog_test(void)
{
	int rc;
	zlog_category_t *zc;

	rc = zlog_init("test_hello.conf");
	if (rc) {
		printf("init failed %d \n",rc);
        zlog_profile(); // 打印详细错误
		return -1;
	}

	zc = zlog_get_category("my_cat");
	if (!zc) {
		printf("get cat fail\n");
		zlog_fini();
		return -2;
	}

	zlog_info(zc, "hello, zlog");

	zlog_fini();
	
	return 0;
}


using namespace Poco::Net;

class EchoConnection : public TCPServerConnection
{
public:
    EchoConnection(const StreamSocket& socket) : TCPServerConnection(socket) {}

    void run() override
    {
        try {
            std::cout << "新客户端连接: " << socket().peerAddress().toString() << std::endl;

            char buffer[1024];
            int n = 0;

            while ((n = socket().receiveBytes(buffer, sizeof(buffer))) > 0) {
                std::cout << "收到 " << n << " 字节: " << std::string(buffer, n) << std::endl;
                socket().sendBytes(buffer, n); // 回显
            }

            std::cout << "客户端断开连接" << std::endl;

        } catch (Poco::TimeoutException& e) {
            std::cerr << "超时: " << e.displayText() << std::endl;
        } catch (Poco::IOException& e) {
            std::cerr << "IO异常: " << e.displayText() << std::endl;
        } catch (Poco::Exception& e) {
            std::cerr << "Poco异常: " << e.displayText() << std::endl;
        } catch (...) {
            std::cerr << "未知异常" << std::endl;
        }
        // Poco 自动关闭 socket，无需手动 cleanup
    }
};

class EchoConnectionFactory : public TCPServerConnectionFactory
{
public:
    TCPServerConnection* createConnection(const StreamSocket& socket)
    {
        return new EchoConnection(socket);
    }
};

int main()
{
    
    const uint16_t PORT = 12345;
    zlog_test();

    int json_cpp_demo(void);
     json_cpp_demo();

    try {
        ServerSocket serverSocket(PORT);
        TCPServer server(new EchoConnectionFactory, serverSocket);

        server.start();
        std::cout << "Poco TCP 服务器启动，监听端口 " << PORT << " ..." << std::endl;

        // 等待用户输入回车退出
        std::cout << "按回车键退出服务器..." << std::endl;
        std::cin.get();

        server.stop();
        std::cout << "服务器已停止。" << std::endl;

    } catch (Poco::Exception& e) {
        std::cerr << "服务器启动失败: " << e.displayText() << std::endl;
        return 1;
    }

    return 0;
}